/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.icee.myth.gm.channelhandler;

import com.icee.myth.gm.GmServer;
import static org.jboss.netty.handler.codec.http.HttpHeaders.*;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*;


import com.icee.myth.gm.db.DbHandler;
import com.icee.myth.gm.admin.UserData;
import com.icee.myth.gm.controller.AbstractController;
import com.icee.myth.gm.controller.ControllerFactory;
import com.icee.myth.utils.LogConsts;
import com.icee.myth.utils.MLogger;
import com.icee.myth.utils.StackTraceUtil;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

/**
 *
 * @author liuxianke
 */
public class HttpServerHandlerToGM extends HttpServerHandler {

    @Override
    public void channelConnected(
            ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        // 判定浏览器ip是否合法
        Channel channel = e.getChannel();
        String browserIP = channel.getRemoteAddress().toString();
        browserIP = browserIP.substring(1, browserIP.indexOf(":"));
//        if (GmServer.INSTANCE.isTrustedBrowser(browserIP)) {
        MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_DEBUG, "Browser[" + browserIP + "] connected.");
//        } else {
//            channel.close();
//            MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Browser[" + browserIP + "] not trusted.");
//        }
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        if (e.getChannel().isOpen()) {
            HttpRequest request = (HttpRequest) e.getMessage();

            if (is100ContinueExpected(request)) {
//                sendError(ctx, BAD_REQUEST);
                send100Continue(e);
//                return;
            }

            String uri = request.getUri();

            System.out.println("Uri " + uri);
            DbHandler dbHandler = new DbHandler(GmServer.INSTANCE.dbHost, GmServer.INSTANCE.dbName);
            JSONObject jobj = (JSONObject) JSONValue.parse(request.getContent().toString(org.jboss.netty.util.CharsetUtil.UTF_8));

            if (uri.equals("/login")) {
                if (jobj != null && jobj.get("username") != null && jobj.get("password") != null) {
                    String userName = (String) jobj.get("username");
                    String password = (String) jobj.get("password");
                    // 从数据库中检索用户信息，并比较密码
                    UserData userData = dbHandler.getUserDataFromDB(userName);
                    if (userData != null) {
                        // 验证密码
                        if (password.equals(userData.passwd)) {
                            // 生成sessionId与用户信息
                            GmServer.INSTANCE.addUserData(userData);
                            HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":0,\"sessionid\":\"" + userData.sessionId + "\"}", null);
                        } else {
                            HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\": " + "\"password error\"}", null);
                        }
                    } else {
                        HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\": " + "\"user not found\"}", null);
                    }
                }
            } else if (uri.startsWith("/public")) {
                HttpServerHandler.handleFileRequest(ctx, e, uri.substring(1, request.getUri().length()), null);
            } else {
                UserData userData = getUserDataFromCache(jobj);
                if (userData == null) {
                    writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\":\"not login\"}", null);
//                    return;   // 注意：不能在这里退出，因为数据库连接没关闭（该注释为LXK添加）
                } else {
                    AbstractController controller = ControllerFactory.buildController(uri);
                    if (controller != null) {
                        controller.init(ctx, request, e, jobj, userData, dbHandler);
                        controller.index();
                    } else {
                        sendError(ctx, FORBIDDEN);
                    }
                }
            }
            dbHandler.close();
        }
    }

    private UserData getUserDataFromCache(JSONObject jobj) {
        String sessionIdString = (String) (jobj.get("sessionid"));
        UserData userData = null;
        if (sessionIdString != null) {
            try {
                Integer sessionId = Integer.valueOf(sessionIdString);
                userData = GmServer.INSTANCE.getUserData(sessionId);
            } catch (NumberFormatException ex) {
                MLogger.getlogger().log(LogConsts.LOGTYPE_DBERR, StackTraceUtil.getStackTrace(ex));
            }
        }
        return userData;
    }
}
